package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.WxConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    WeChatProperties weChatProperties;

    @Autowired
    UserMapper userMapper;

    /**
     * 用户登录
     *
     * @return
     * @author 小陈
     * @Params:
     * @DateTime:
     */
    @Override
    public User checkLogin(UserLoginDTO userLoginDTO) {
        //1.使用httpClient 和为服务器交互（验证code是否正确）
        Map<String, String> param = new HashMap<>();
        param.put("appid", weChatProperties.getAppid());
        param.put("secret", weChatProperties.getSecret());
        param.put("js_code", userLoginDTO.getCode());
        param.put("grant_type", "authorization_code");

        String wxResult = HttpClientUtil.doGet(WxConstant.CODE_CHECK_URL, param);// 登录凭证校验
        log.info("微信服务验证code的结果：" + wxResult);

        //2.判断结果openid是否存在
        //解析json字符串
        String openid = JSONObject.parseObject(wxResult).getString("openid");
        //如果不存在，微信用户不合法，直接抛异常
        if (openid == null) {
            throw new LoginFailedException("非法微信用户，请切换账号");
        }

        //3.判断当前微信用户是否是新用户
        //如果是新用户，添加用户信息到user表中:select *from user where openid=?
        User user = userMapper.selectByOpenid(openid);
        if (user==null){
            //新用户: insert inio user values():
            user = User.builder()
                    .createTime(LocalDateTime.now())
                    .openid(openid)
                    .build();
            userMapper.insert(user); //设置主键返回
        }
        //4.封装返回验证结果

        return user;
    }
}
